package com.qf.util;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @ClassName ConnectionUtils
 * @Description TODO
 * @Author 86181
 * @Date 2022/8/31 17:35
 * @Version 1.0
 **/
public class ConnectionUtils {
    //线程绑定
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
    //connection来源 datasource

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    //将线程绑定
    public Connection getConnection() {
        Connection connection = threadLocal.get();
        if (connection==null){
            try {
                connection = dataSource.getConnection();
                threadLocal.set(connection);
                return connection;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }


    //解绑
    public  void close(){
        threadLocal.remove();
    }

}
